//Crazy Intro, Copyright 2009 WiiCrazy/I.R.on of Irduco (nejat@tepetaklak.com)
//Distributed under the terms of the GNU GPL v2.0
//See http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt for more information

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <gccore.h>
#include <errno.h>
#include <fat.h>

#include "common.h"

FILE * HEDE_OpenContent(char * filename) 
{
	FILE * fp;
	fp = fopen(filename,"rb");
	return fp;
}


//Making it compatible to non-buffer-aligned reads
s32 HEDE_ReadContent(FILE * file, u8 *data, u32 data_size)
{
	const BUFFERSIZE=4096;
	u8 * datap;
	datap=data;
	u8 buf[BUFFERSIZE];
	u32 count = (data_size/BUFFERSIZE);  //Count of full filled buffers...
	u32 leftOver = data_size%BUFFERSIZE; //The extra data we'll read out of the loop

	s32 totalread = 0;
	s32 sessionread = 0;
	//printf("Reading %x bytes into %x\n", data_size, (u32)data);
	while(count--) 
	{
		totalread+=fread(buf, 1,BUFFERSIZE, file);
		memcpy(datap, buf, BUFFERSIZE); //Copy full buffer
		datap+=BUFFERSIZE;
		
	}
	//We read the aligned ones... now we should read the non-aligned part
	if (leftOver>0) 
	{
		//printf("Has %x bytes left\n", leftOver);
		//sleep(3);

		sessionread=fread(buf, 1,leftOver, file);
		if (sessionread!=leftOver) 
		{
			//printf("Non-aligned read failed! Exiting!\n");
			//sleep(3);
		}
		memcpy(datap, buf, leftOver); //Copy only the leftOver bytes...
		datap+=leftOver;
		totalread+=sessionread;
	}
	//printf("Read %x bytes\n", totalread);
	return totalread;
}

s32 HEDE_ReadFully(FILE * file, u8 *data, u32 data_size)
{
	s32 totalread;
	totalread=fread(data, 1,data_size, file);
	return totalread;
}



s32 HEDE_SeekContent(FILE * file, s32 where, s32 whence)
{
	return fseek(file, where, whence);
}

s32 HEDE_CloseContent(FILE * file)
{
	return fclose(file);
}



